package com.sdy.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;
import com.sdy.config.Constant;
import com.sdy.model.Modeinfo;
import com.sdy.util.ImageDecode;

public class ModelInfoController extends Controller {
	
	private Modeinfo modeinfodao = Modeinfo.dao;
	
	/**
	 * 添加信息
	 */
	public void saveModelInfo(){
		List<UploadFile> files = getFiles();
		List<Modeinfo> modes = new ArrayList<Modeinfo>();
		for (int i=0; i<getParaToInt("size"); i++) {
			modes.add(getModel(Modeinfo.class, "modelinfo_" + i + ""));
		}
		for(int i=0;i<files.size();i++){
			if(files.get(i).getFileName() != null){
				String filePath = files.get(i).getSaveDirectory();
				String fileName = UUID.randomUUID().toString()+"."+files.get(i).getOriginalFileName().split("\\.")[1];
				//图片压缩
				//ImageDecode.createThumbnail(filePath+"/"+files.get(i).getFileName(), filePath+"/"+files.get(i).getFileName(), 970, 540); 
				files.get(i).getFile().renameTo(new File(filePath+"/"+fileName));
				modes.get(Integer.parseInt(files.get(i).getParameterName())).set("textValue", "/upload/"+fileName);
			}
		}
		modeinfodao.batchDeleteMode(getParaToInt("modelId"));
		modeinfodao.batchSaveMode(modes);
		redirect("/admin/modeinfo/rendPage?type=admin&modelId="+getParaToInt("modelId"));
	}
	
	public void rendPage(){
		List<Modeinfo> modes = modeinfodao.findMode(getParaToInt("modelId"));
		for(int i=0;i<modes.size();i++){
			setAttr("modelinfo_"+i+"", modes.get(i).get("textValue"));
		}
		render(getRendUrl(getParaToInt("modelId"),getPara("type")));
	} 
	
	/**
	 * 根据模块ID获取跳转的URL
	 * @param modelId
	 * @return
	 */
	private String getRendUrl(int modelId,String type){
		String rendUrl = "";
		if("admin".equals(type)){
			switch (modelId) {
			case Constant.IDEA:
				rendUrl = "/admin/idea.jsp";
				break;
			case Constant.PAY:
				rendUrl = "/admin/pay.jsp";
				break;
			case Constant.DOWNLOAD:
				rendUrl = "/admin/download.jsp";
				break;
			case Constant.PLAN:
				rendUrl = "/admin/plan.jsp";
				break;
			default:
				rendUrl = "/admin/idea.jsp";
				break;
			}
		}
		if("index".equals(type)){
			switch (modelId) {
			case Constant.IDEA:
				rendUrl = "/index/idea.jsp";
				break;
			case Constant.PAY:
				rendUrl = "/index/pay.jsp";
				break;
			case Constant.DOWNLOAD:
				rendUrl = "/index/download.jsp";
				break;
			case Constant.PLAN:
				rendUrl = "/index/plan.jsp";
				break;
			default:
				rendUrl = "/index/idea.jsp";
				break;
			}
		}
		return rendUrl;
	}
	
	public void message(){
		render("/index/message.jsp");
	}
}
